import { AstroError } from 'astro/errors'
import fs from 'fs/promises'

let highestVer: string, highestVal = 0

export type LangType = 'zh_cn' | 'en_us'

await fs.readdir("extract/").then(files => {
  files.map(file => {
    // file name like 1.1.4.jar
    const ver = file.split(".").slice(0, 3).reduce((a, b) => a * 1 + parseInt(b) * 1, 0)
    if (ver > highestVal) {
      highestVal = ver
      highestVer = file.replace(".jar", "")
    }
  })
})

export default async function getTranslateByKey(key: string, lang: LangType = 'zh_cn', ver?: string) {
  if (!key.length) throw new AstroError("查找翻译资源的key为空！")

  let res: string = ""

  const FinalVer = ver || highestVer

  const BasicExtraPath = `./extract/${FinalVer}/lang`;
  const extractPath = `${BasicExtraPath}/${lang}.json`;
  const cacheExtractPath = `./.cache/extract/temp/${FinalVer}/assets/providencraft/lang/${lang}.json`;

  let readRes: Record<string, string> = {}
  // first try open extract
  try {
    readRes = JSON.parse(await fs.readFile(extractPath, "utf-8"));
  } catch (e) {
    // second try open cache
    try {
      readRes = JSON.parse(await fs.readFile(cacheExtractPath, "utf-8"));
      await fs.mkdir(BasicExtraPath, { recursive: true });
      await fs.writeFile(extractPath, JSON.stringify(readRes, null, 2));
    } catch (e) {
      console.log(e);
    }
  }

  res = readRes[key]

  if (!res.length) throw new AstroError("找不到翻译资源: " + key)

  return res
}
